/*
 * @Author: your name
 * @Date: 2021-02-15 19:45:41
 * @LastEditTime: 2021-02-19 11:16:06
 * @LastEditors: Please set LastEditors
 * @Description:添加工程
 * @FilePath: \jianfa-api\routes\admin\projectCode.js
 */

const express = require('express');
const router = express.Router();
const Result = require('../../models/result.js');
const upload = require('../../utils/multer.js');
const { addProjectCodeService, getProjectListService, editProjectService, getPidService , delProService} = require('../../service/projectCodeService')
const { addProjectImgService } = require('../../service/imgService')
// 添加项目
router.post('/add', async (req, res, next) => {
 const { status, results: { insertId } } = await addProjectCodeService(req.body)
 if (status) {
  new Result({
   pid:insertId
  }, '添加成功').success(res)
 } else {
  new Result({}, '添加失败').fail(res)
 }
})
//获取自增id即将生成的项目pid值
router.get('/get_pid', async (req, res, next) => {
 const { status, results: [{ pid }] } = await getPidService()
 if (status) {
  new Result({ pid }, '获取成功').success(res)
 } else {
  new Result({}, '获取失败').fail(res)
 }
})
// 添加项目图片
router.post('/add_pro_img', upload.array('photos'), async (req, res, next) => {
 let imgsInfo = [] //图片信息数组
 req.files.forEach((file) => {
  let obj = {}
  obj.name = file.filename
  obj.imgPath = `public/img/${obj.name}`
  obj.path = file.path
  imgsInfo.push(obj)
 })
 const { status } = await addProjectImgService(imgsInfo, req.body.pid)
 if (status) {
  const data = {
   imgsInfo,
   count: imgsInfo.length
  }
  new Result(data, '上传成功').success(res)
 } else {
  new Result({}, '上传失败').fail(res)
 }
})
//根据id删除工程
router.post('/del_pro', async (req, res, next) => {
 const { status } = await delProService(req.body)
 if (status) {
  new Result({}, '删除成功').success(res)
 } else {
  new Result({}, '删除失败').fail(res)
 }
})
// 查询项目列表
router.post('/project_list', async (req, res, next) => {
 const { status, results } = await getProjectListService(req.body)
 if (status) {
  let data = { results, total: global.all_let.TOTAL }
  global.all_let.TOTAL != null ? null : delete data.total
  new Result(data, '查询成功').success(res)
 } else {
  new Result({}, '添加失败').fail(res)
 }
})
// 编辑项目
router.post('/edit', async (req, res, next) => {
 const { status } = await editProjectService(req.body)
 if (status) {
  new Result({}, '编辑成功').success(res)
 } else {
  new Result({}, '编辑失败').fail(res)
 }
})

module.exports = router;